//
//  PopCalendarViewController.m
//  AlinkDemo
//
//  Created by Vincent on 2017/10/29.
//  Copyright © 2017年 aliyun. All rights reserved.
//

#import "PopCalendarViewController.h"

@interface PopCalendarViewController ()<FSCalendarDataSource,FSCalendarDelegate>
@property (nonatomic,strong) NSArray *datesWithEvent;
@property (strong, nonatomic) NSDateFormatter *dateFormatter;

@property (nonatomic,strong) FSCalendar *calendar;
@property (nonatomic,strong) UIButton *nextButton;
@property (nonatomic,strong) UIButton *previousButton;
@property (strong, nonatomic) NSCalendar *gregorian;
@end

@implementation PopCalendarViewController



- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    NSLocale *chinese = [NSLocale localeWithLocaleIdentifier:@"zh-CN"];
    self.gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];

    self.dateFormatter = [[NSDateFormatter alloc] init];
    self.dateFormatter.locale = chinese;
    self.dateFormatter.dateFormat = @"yyyy-MM-dd";
    

    FSCalendar *calendar = [[FSCalendar alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 300)];
    calendar.dataSource = self;
    calendar.delegate = self;
    calendar.locale =chinese;
    calendar.today  = self.currentDate;
    [self.view addSubview:calendar];

    self.calendar = calendar;
//    self.datesWithEvent = @[@"2016-12-03",
//                            @"2016-12-07",
//                            @"2016-12-15",
//                            @"2017-11-25"];
    calendar.appearance.selectionColor = UIColorFromRGB(0x02C7B2);
    calendar.appearance.eventSelectionColor = [UIColor whiteColor];
    calendar.appearance.eventDefaultColor = UIColorFromRGB(0x02C7B2);
    calendar.appearance.headerTitleColor = UIColorFromRGB(0x808080);
    calendar.appearance.weekdayTextColor = UIColorFromRGB(0x808080);
    calendar.appearance.todayColor = UIColorFromRGB(0x02C7B2);

    UIButton *previousButton = [UIButton buttonWithType:UIButtonTypeCustom];
    previousButton.frame = CGRectMake(0, 0, 95, 34);
    previousButton.backgroundColor = [UIColor whiteColor];
    previousButton.titleLabel.font = [UIFont systemFontOfSize:15];
    [previousButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
    [previousButton setTitle:@"◀" forState:UIControlStateNormal];
    [previousButton addTarget:self action:@selector(previousClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:previousButton];
    self.previousButton = previousButton;

    UIButton *nextButton = [UIButton buttonWithType:UIButtonTypeCustom];
    nextButton.frame = CGRectMake(CGRectGetWidth(self.view.frame)-95, 0, 95, 34);
    nextButton.backgroundColor = [UIColor whiteColor];
    nextButton.titleLabel.font = [UIFont systemFontOfSize:17];
    [nextButton setTitle:@"▶" forState:UIControlStateNormal];
    [nextButton addTarget:self action:@selector(nextClicked:) forControlEvents:UIControlEventTouchUpInside];
    [nextButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];

    [self.view addSubview:nextButton];
    self.nextButton = nextButton;
    
    [self getEventDate];
    
}

-(void)getEventDate{
    
    
    
    NSDate *nextDay = [NSDate dateWithTimeInterval:30*24*60*60 sinceDate:self.calendar.currentPage];//后一天
    long long startTime = ((long long)[self.calendar.currentPage timeIntervalSince1970])*1000;
    long long endTime = ((long long)[nextDay timeIntervalSince1970])*1000;
    
    
    if (self.isAlarm) {
        [YKBusinessFramework equesGetAlarmMessageList:self.bid startTime:startTime endTime:endTime limitCount:1000];
        
    }else if(self.isRings){
        [YKBusinessFramework equesGetRingRecordList:self.bid startTime:startTime endTime:endTime limitCount:1000];
    }else{
    
        [self.dateFormatter setDateFormat:@"yy-MM-dd"];
        
        NSFileManager *fm = [NSFileManager defaultManager];
        
        NSString *path = [ NSSearchPathForDirectoriesInDomains( NSDocumentDirectory , NSUserDomainMask , YES ) objectAtIndex : 0 ];
        
        path = [[path stringByAppendingPathComponent:@"capture"] stringByAppendingPathComponent:self.bid];
        NSError *error ;
        NSArray *images = [fm contentsOfDirectoryAtPath:path error:&error];
        NSLog(@"%@",path);
        NSLog(@"%@",images);
        
        NSMutableArray *dates = [[NSMutableArray alloc] init];
        for (NSString *name in images) {
            NSDictionary *dict=[fm attributesOfItemAtPath:[path stringByAppendingPathComponent:name] error:&error];
            if(dict!=nil)
            {
                NSLog(@"filesize =  %llu ",[dict fileSize]);
                if (dict.fileSize>64) {
                    [dates addObject:name];
                }
                
            }
        }

        self.datesWithEvent = dates;
    }
}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(onMessageResult:) name:equesOnMessageResultNotification object:nil];
    
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
}



#pragma mark 收到的消息
- (void)onMessageResult:(NSNotification *)notification{
    
    [SVProgressHUD dismiss];
    
    NSDictionary *messageResult = [notification object];
    
    NSString *method = messageResult[@"method"];
    
    if (self.isAlarm) {
        if ([method isEqualToString:@"almlist"]){
            NSArray *alarms = [messageResult objectForKey:@"alarms"];
            
            NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
            
            for (NSDictionary *alarm in alarms) {
                
                long long time = [alarm[@"time"] longLongValue]/1000;
                
                NSDate *date = [NSDate dateWithTimeIntervalSince1970:time];
                
                NSString *ring = [self.dateFormatter stringFromDate:date];
                
                [dict setValue:@"1" forKey:ring];
            }
            
            self.datesWithEvent = [dict allKeys];
            [self.calendar reloadData];
        }
    }else if(self.isRings){
        if ([method isEqualToString:@"ringlist"]){
            
            NSArray *rings = [messageResult objectForKey:@"rings"];
            
            NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
            
            for (NSDictionary *ring in rings) {
                
                long long time = [ring[@"ringtime"] longLongValue]/1000;
                
                NSDate *date = [NSDate dateWithTimeIntervalSince1970:time];
                
                NSString *ring = [self.dateFormatter stringFromDate:date];
                
                [dict setValue:@"1" forKey:ring];
            }
            
            self.datesWithEvent = [dict allKeys];
            [self.calendar reloadData];
        }
        
    }

    
}



- (void)previousClicked:(id)sender
{
    NSDate *currentMonth = self.calendar.currentPage;
    NSDate *previousMonth = [self.gregorian dateByAddingUnit:NSCalendarUnitMonth value:-1 toDate:currentMonth options:0];
    [self.calendar setCurrentPage:previousMonth animated:YES];
    [self getEventDate];
}

- (void)nextClicked:(id)sender
{
    NSDate *currentMonth = self.calendar.currentPage;
    NSDate *nextMonth = [self.gregorian dateByAddingUnit:NSCalendarUnitMonth value:1 toDate:currentMonth options:0];
    [self.calendar setCurrentPage:nextMonth animated:YES];
    [self getEventDate];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)calendar:(FSCalendar *)calendar didSelectDate:(NSDate *)date atMonthPosition:(FSCalendarMonthPosition)monthPosition{
    if (self.selectDateBlock) {
        
        self.selectDateBlock(date);
    }
    [self.mz_formSheetPresentingPresentationController dismissViewControllerAnimated:YES completion:nil];
}


- (NSInteger)calendar:(FSCalendar *)calendar numberOfEventsForDate:(NSDate *)date
{
    if ([self.datesWithEvent containsObject:[self.dateFormatter stringFromDate:date]]) {
        return 1;
    }
    return 0;
}
- (NSDate *)maximumDateForCalendar:(FSCalendar *)calendar
{
    NSDate *date = [NSDate date];
    [self.dateFormatter stringFromDate:date];
    return date;
}

@end
